package com.gxa.sso.result;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * Created by zxd on 2020/11/16
 **/
public class ResultUtils {


    /**
     * 构建成功的返回
     * @param obj
     * @param count
     * @return
     */
    public static Result buildSuccess(Object obj,Long count){
        return new Result(0, "", count, obj);
    }

    /**
     * 构建成功的返回
     * @param obj
     * @return
     */
    public static Result buildSuccess(Object obj){
        return buildSuccess(obj,null);
    }

    /**
     * 构建成功的返回
     * @return
     */
    public static Result buildSuccess(){
        return buildSuccess(null);
    }

    /**
     * 构建失败的返回
     * @param code
     * @param message
     * @return
     */
    public static Result buildFail(Integer code,String message){
        return new Result(code, message, null, null);
    }


    /**
     * 构建失败的返回 枚举版本
     * @param messageCode
     * @return
     */
    public static Result buildFail(MessageCode messageCode){
        return buildFail(messageCode.getCode(),messageCode.getMessage());
    }


    public  static Result getErrorResult(BindingResult bindingResult) {
        List<ObjectError> errors = bindingResult.getAllErrors();
        //让前端看着更舒服 使用更方便
        StringBuilder sb=new StringBuilder();
        errors.forEach(error->{
            sb.append(error.getDefaultMessage()+",");
        });
        System.out.println(sb.toString());
        return ResultUtils.buildFail(50000,sb.toString().substring(0,sb.toString().length()-1));
    }


}
